package org.datascooter.extension;

import java.io.IOException;
import java.net.URL;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IProduct;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;

public class EclipsePathResolver {

	private static final String ROOT = "/";

	public static String resolvePath(String fileName) throws IOException {
		IProduct product = Platform.getProduct();
		if (product != null) {
			return resolvePath(product.getDefiningBundle(), fileName);
		}
		return fileName;
	}

	public static String resolvePath1(String fileName) {
		IProduct product = Platform.getProduct();
		if (product != null) {
			try {
				return resolvePath(product.getDefiningBundle(), fileName);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return fileName;
	}

	public static String resolveProjectPath() {
		return Platform.getLocation().toFile().getParentFile().getPath();
	}

	public static String resolvePath(String bundleName, String fileName) throws IOException {
		return resolvePath(Platform.getBundle(bundleName), fileName);
	}

	public static String resolvePath(Bundle bundle, String fileName) throws IOException {
		URL url = FileLocator.find(bundle, new Path(ROOT + fileName), null); //$NON-NLS-1$
		if (url == null) {
			return fileName;
		}
		return FileLocator.toFileURL(url).getPath();
	}

	public static URL getURL(Bundle bundle, String fileName) throws IOException {
		URL url = FileLocator.find(bundle, new Path(ROOT + fileName), null); //$NON-NLS-1$
		if (url == null) {
			return null;
		}
		return FileLocator.toFileURL(url);
	}
}
